﻿using EquipmentAlarmSystem.Service.Models.Enum;
using System.Text.Json;

namespace 设备报警系统客户端
{
    public partial class HomePage : Form
    {
        public HomePage()
        {
            InitializeComponent();

            //外部设备状态标识
            new Task(() =>
            {
                bool isTrue = false;
                while (true)
                {
                    try
                    {
                        string str = Basic.HttpGet($"/AlarmSending/GetSmsAlarmStatus");

                        if (bool.Parse(str))
                        {
                            if (isTrue)
                            {
                                pictureBox1.Image = VerificationServices.CropToCircle(Color.Lime, 30);
                                isTrue = false;
                            }
                            else
                            {
                                pictureBox1.Image = VerificationServices.CropToCircle(Color.Transparent, 30);
                                isTrue = true;
                            }
                        }
                        else
                        {
                            pictureBox1.Image = VerificationServices.CropToCircle(Color.Red, 30);
                        }
                        Thread.Sleep(1 * 1000);
                    }
                    catch (Exception)
                    {
                    }
                }
            }).Start();
        }

        /// <summary>
        /// 刷新时间
        /// </summary>
        int RefreshTime = 2 * 1000;

        List<DeviceInformation> homeData;
        private void HomePage_Load(object sender, EventArgs e)
        {
            HomeData.DefaultCellStyle.Font = new Font("Microsoft YaHei UI", 10F);
            HomeData.AllowUserToResizeRows = false; // 禁止用户调整行高
            HomeData.AllowUserToResizeColumns = false; // 禁止用户调整列宽
            HomeData.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            HomeData.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells; // 所有行都根据内容自动调整大小       
            HomeData.RowTemplate.Height = 35;//行高设置
            HomeData.RowTemplate.MinimumHeight = 35;

            // 获取用户目录的Documents文件夹路径  
            string userDocumentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            // 定义要创建的文件名（包括路径）  
            string filePath = Path.Combine(userDocumentsPath, "EquipmentAlarmSystem", "ServerAddress.txt");

            try
            {
                if (File.Exists(filePath))
                {
                    Basic.ServerAddr = File.ReadAllText(filePath);
                }
                else
                {
                    if (new 服务器配置().ShowDialog() == DialogResult.OK)
                    {
                        Basic.ServerAddr = File.ReadAllText(filePath);
                    }
                }
            }
            catch (Exception)
            {

            }
            label2.Text = $"客户端编号：{Basic.GetSystemId()}";
            //获取基础配置
            Basic.GetConfig();
            if (Basic.Config.ServiceType == ServerType.Master)
            {
                label4.Text = "服务：主站";
            }
            if (Basic.Config.ServiceType == ServerType.Slave)
            {
                label4.Text = "服务：从站";
            }

            string req = Basic.HttpGet($"/Currency/GetGrouping?id={Basic.GetSystemId()}");

            try
            {
                //获取授权分组
                cbConnectToServer.DataSource = JsonSerializer.Deserialize<List<string>>(req);
            }
            catch (Exception)
            {
                MessageBox.Show(req, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Application.Exit();
            }
            try
            {
                if (cbConnectToServer.Text.Length > 2)
                {
                    //获取授权数据
                    homeData = JsonSerializer.Deserialize<List<DeviceInformation>>(Basic.HttpGet($"/Currency/ObtainGroupData?id={Basic.GetSystemId()}&grouping={cbConnectToServer.Text}"));
                    HomeData.Rows.Clear();
                    foreach (var item in homeData)
                    {
                        int index = HomeData.Rows.Add();
                        HomeData.Rows[index].Cells[0].Value = item.Id;
                        HomeData.Rows[index].Cells[1].Value = item.Name;
                        HomeData.Rows[index].Cells[2].Value = item.Describe;
                        HomeData.Rows[index].Cells[3].Value = "编辑";
                        HomeData.Rows[index].Cells[4].Value = "";
                        HomeData.Rows[index].Cells[5].Value = "开启";
                    }
                }
            }
            catch (Exception)
            {

            }

            RefreshLogs();
        }


        /// <summary>
        /// 刷新日志
        /// </summary>
        private void RefreshLogs()
        {
            new Task(() =>
            {
                while (true)
                {
                    try
                    {
                        //在运行设备刷新
                        string req = Basic.HttpGet("/Equipment/GetEquipmentOperationList");

                        var runningState = JsonSerializer.Deserialize<List<string>>(req);
                        this.Invoke(new Action(() =>
                        {
                            for (int i = 0; i < HomeData.RowCount; i++)
                            {
                                if (runningState.Contains(Basic.iSNull(HomeData.Rows[i].Cells[0].Value)))
                                {
                                    HomeData.Rows[i].Cells[4].Value = "运行中";
                                    HomeData.Rows[i].Cells[5].Value = "关闭";
                                }
                                else
                                {
                                    HomeData.Rows[i].Cells[4].Value = "";
                                    HomeData.Rows[i].Cells[5].Value = "开启";
                                }
                            }
                        }));
                    }
                    catch (Exception)
                    {
                    }
                    Thread.Sleep(RefreshTime);
                }
            }).Start();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void HomeData_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

            //按钮事件 5
            DataGridViewRow row = HomeData.Rows[e.RowIndex];
            int cell1 = 5;
            string id = Basic.iSNull(row.Cells[0].Value.ToString());
            if (e.ColumnIndex == cell1)
            {
                if (row.Cells[cell1].Value is null)
                {
                    return;
                }
                string cellValue = row.Cells[cell1].Value.ToString()!;

                //服务开关
                if (cellValue == "关闭")
                {
                    DialogResult dialogResult = MessageBox.Show($"正在关闭【{row.Cells[1].Value.ToString()}】设备报警推送服务，请确认是否继续！", "操作确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

                    if (dialogResult != DialogResult.Yes)
                    {
                        return;
                    }
                    MessageBox.Show(Basic.HttpGet($"/Equipment/Close?id={id}"));
                }
                if (cellValue == "开启")
                {
                    // 开启报警服务
                    MessageBox.Show(Basic.HttpGet($"/Equipment/Open?id={id}"));
                }
            }

            //编辑配 4
            int cell2 = 3;
            if (e.ColumnIndex == cell2)
            {
                //检查按钮是否有值
                if (row.Cells[cell2].Value is null)
                {
                    return;
                }
                string cellValue = row.Cells[cell2].Value.ToString()!;

                if (cellValue != "编辑")
                {
                    return;
                }
                if (MessageBox.Show($"尝试编辑配置文件，请确认是否继续！", "操作确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) != DialogResult.Yes)
                {
                    return;
                }
                //实例化配置编辑页面
                //row.Cells[0].Value

                Protocol protocol = Protocol.S7;

                foreach (var item in homeData)
                {
                    if (id == item.Id)
                    {
                        protocol = item.Protocol;
                    }
                }
                Form form = new();

                if (protocol == Protocol.S7)
                {
                    form = new 西门子S7设备添加修改(id);
                }
                else if (protocol == Protocol.ModbusTcp)
                {
                    form = new ModbusTcp设备添加修改(id);
                }
                else
                {
                    MessageBox.Show($"未支持协议！", "操作错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    form.Dispose();
                    return;
                }
                var dialogResult = form.ShowDialog();

                if (dialogResult == DialogResult.OK)
                {

                }
            }
        }

        private void cbConnectToServer_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (cbConnectToServer.Text.Length > 1)
                {
                    //获取授权数据
                    homeData = JsonSerializer.Deserialize<List<DeviceInformation>>(Basic.HttpGet($"/Currency/ObtainGroupData?id={Basic.GetSystemId()}&grouping={cbConnectToServer.Text}"));
                    HomeData.Rows.Clear();
                    foreach (var item in homeData)
                    {
                        int index = HomeData.Rows.Add();
                        HomeData.Rows[index].Cells[0].Value = item.Id;
                        HomeData.Rows[index].Cells[1].Value = item.Name;
                        HomeData.Rows[index].Cells[2].Value = item.Describe;
                        HomeData.Rows[index].Cells[3].Value = "编辑";
                        HomeData.Rows[index].Cells[4].Value = "";
                        HomeData.Rows[index].Cells[5].Value = "开启";
                    }
                }
            }
            catch (Exception)
            {

            }
        }

        private void btnLog_Click(object sender, EventArgs e)
        {
            日志.ShowForm();
        }
    }
}
